package com.xtz.controller;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xtz.vo.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * date: 2022/5/10 15:51
 *
 * @author xietianze
 */
@RestController
@RequestMapping("common")
public class CommonController {
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
        String contentType = file.getContentType();
        if (StrUtil.isEmpty(contentType)){
            return new Result(0,"文件缺失",null,null);
        }
        //创建一个文件名
        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + "." + contentType.split("/")[1];

        //调用oss的方法
        // build(endponit节点 ,accesskey,secret)
        OSS ossClient = new OSSClientBuilder().build(
                "oss-cn-beijing.aliyuncs.com",
                        "LTAI5tFkKbUJ1WQNyxLLtfbB",
                        "nS8vobuae5pkxN9wU51CndChVx2i9V");
        //bucketName
        ossClient.putObject("xtz-test",filename,file.getInputStream());

        ossClient.shutdown();

        return new Result(1,null,"https://xtz-test.oss-cn-beijing.aliyuncs.com"+"/"+filename,null);

    }
}
